% Final Project for ENGR 30
% author: cbalzarano
% -------------------------------------------------------------------------
% For this code to run, "MATLAB Support Package for USB Webcams" is
% required. MATLAB Support Package for USB Webcams can be downloaded 
% through the following code,
% matlab.internal.addons.showAddon('USBWEBCAM').
% -------------------------------------------------------------------------
% This code tracks circular objects from webcam video and animates the
% movement in real time on a matlab plot. The code works in a while 
% loop by taking a snapshot of the webcam footage and searching for
% circles that have a radius of a set range. The code then finds the x,
% y components of the center of the circle and those components are
% plotted on an x,y graph. The while loop allows for the animation to
% continue as long as the circle is within the view of the webcam.
% This works for multiple circular objects at once. :)
% -------------------------------------------------------------------------

clear();
%"160x120
%"Logi C615 HD WebCam"
cam = webcam("Logi C615 HD WebCam");
cam.Resolution = "320x240";
cam.Brightness = 255;
preview(cam)
img = snapshot(cam);
grey_img = im2gray(img);

%! use this to get the diameter of the circle
% imshow(grey_img);
% d = drawline;
% pos = d.Position;
% diffPos = diff(pos);
% diameter = hypot(diffPos(1),diffPos(2))
%! diameter = 33.5014 pixels        <=== useful to keep track of diameter

%! The following code works for finding a circle of a given radius range
%! I left this in to show my proccess as I had to figure this out
%! before setting up the loop. It is also helpful for referance.

% [centers,radii] = imfindcircles(img,[12 18], ...
%     ObjectPolarity="dark", Sensitivity=0.96);
% x = centers(:,1);
% y = centers(:,2);
% r = (3/2)*radii;
% imshow(grey_img);
% axis on
% hold on
% plot(x,y, 'ro', 'MarkerSize', r)
% hold off

x = 0;
y = 0;
court_x = [9, 9, 305, 305, 9];
court_y = [77, 213, 213, 77,  77];
hold on
plot(court_x,court_y,'k-')
plt_hnd1 = plot(x,y, 'ro', 'MarkerSize', 27);
axis([0 321 0 241])
hold off
t = 0;
while true
    img = snapshot(cam);

    [centers,radii] = imfindcircles(img,[12 16],ObjectPolarity="dark", ...
                      Sensitivity=0.96);
    x = centers(:,1);
    y = 240 - centers(:,2);

    set(plt_hnd1,'XData',x)
    set(plt_hnd1,'YData',y)
    drawnow;
    t = t + 1
end 